<script setup>
import {
    Edit,
    Delete,
    Close
} from '@element-plus/icons-vue'


import { ref } from 'vue'


const subjects = ref([
    {
        "id": 0,
        "subjectValue": "语文",
    },
    {
        "id": 1,
        "subjectValue": "数学",
    },
    {
        "id": 2,
        "subjectValue": "英语",
    },
    {
        "id": 3,
        "subjectValue": "科学",
    }
])


const options = ref([
  {
    "id": 0,
    "contentValue": "正确",
  },
  {
    "id": 1,
    "contentValue": "错误",
  }
])



const gradeTypes = ref([
    {
        "id": 0,
        "contentValue": "低年级",
    },
    {
        "id": 1,
        "contentValue": "高年级",
    }
])

const questionTypes = ref([
    {
        "id": 0,
        "questionValue": "选择题",
    },
    {
        "id": 1,
        "questionValue": "判断题",
    }
])

//用户搜索时选中的分类id
const subject = ref('')



//用户搜索时选中的发布状态
const state = ref('')




const questions = ref([


])

const account = ref('')

const name = ref('')

const day = ref('')

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(15)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    questionList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    questionList()
}


import {
  questionAddService,
  questionListService,
  questionDeleteService,
  questionUpdateService,
  questionPublishService,
  questionDataListService, knowledgeDataListService
} from '@/api/question.js'



import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const questionModel = ref({

})


//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();


//上传成功的回调函数
const uploadSuccess = (result) => {
    questionModel.value.imgUrl = result.data;
    console.log(result.data);
}

const uploadAudioSuccess = (result) => {
    questionModel.value.audioUrl = result.data;
    console.log(result.data);
}


//添加文章
import { ElMessage } from 'element-plus'
const addQuestion = async (clickState) => {
    //把发布状态赋值给数据模型
    questionModel.value.state = clickState;

    //调用接口
    let result = await questionAddService(questionModel.value);

    ElMessage.success(result.msg ? result.msg : '添加成功');

    //让抽屉消失
    visibleDrawer.value = false;

    //刷新当前列表
    questionList()
}

//编辑分类
const updateQuestion = async () => {
    //调用接口
    let result = await questionUpdateService(questionModel.value);

    ElMessage.success(result.msg ? result.msg : '修改成功')

    //调用获取所有分类的函数
    questionList();

    //隐藏弹窗
    visibleDrawer.value = false;
}


//获取文章列表数据
const questionList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      account:account.value?account.value:null,
      name:name.value?name.value:null,
      day:day.value?day.value:null,
        subject: subject.value

    }

    let result = await knowledgeDataListService(params);

    //渲染视图
    total.value = result.data.total;
    questions.value = result.data.records;

}


questionList();



//删除分类
import { ElMessageBox } from 'element-plus'
import { useFavicon } from '@vueuse/core';
const delQuestion = (row) => {
    //提示用户  确认框

    ElMessageBox.confirm(
        '你确认要删除该题目信息吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //调用接口
            let result = await questionDeleteService(row.id);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            //刷新列表
            questionList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消了删除',
            })
        })
}


//定义变量,控制标题的展示
const title = ref('')
const showQuestion = (row) => {
    visibleDrawer.value = true, title.value = '编辑题目'
    questionModel.value.subject = row.subject;
    questionModel.value.gradeType = row.gradeType;
    questionModel.value.type = row.type;
    questionModel.value.imgUrl = row.imgUrl;
    questionModel.value.audioUrl = row.audioUrl;
    questionModel.value.content = row.content;
    questionModel.value.id = row.id;
    questionModel.value.rightAnswer = row.rightAnswer;
    questionModel.value.wrongOption2 = row.wrongOption2;
    questionModel.value.wrongOption3 = row.wrongOption3;
    questionModel.value.wrongOption4 = row.wrongOption4;

}

//清空模型的数据
const clearData = () => {

    questionModel.value.subject = '';
    questionModel.value.gradeType = '';
    questionModel.value.type = 1;
    questionModel.value.imgUrl = '';
    questionModel.value.audioUrl = '';
    questionModel.value.content = '';
    questionModel.value.id = '';
    questionModel.value.rightAnswer = '';
    questionModel.value.wrongOption2 = '';
    questionModel.value.wrongOption3 = '';
    questionModel.value.wrongOption4 = '';
}

const delAudio = () => {
    questionModel.value.audioUrl = '';
}
const delImg = () => {
    questionModel.value.imgUrl = '';
}

const selected = (row, index) => {
    return questions.value[index].publishState == 0
}

let select = []
const publish = async () => {
    console.log(select)
    if (select.length === 0) {
        ElMessage.error("请选择要发布的题目")
        return
    }
    let ids = []
    select.forEach(element => {
        ids.push(element.id)
    });
    let params = {
        ids: ids
    }
    let result = await questionPublishService(params);

    questionList();

}
const handleSelectionChange = (val) => {
    select = val;
}

const showState = ref(0)
const changeQuestionType = (val) => {
    if (val == 0) {
        showState.value = 1;
    } else {
        showState.value = 0;
    }
}


</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>学生知识点情况查询</span>

            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
          <el-form-item label="时间：">
            <el-date-picker
                v-model="day"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="账号：">
            <el-input  v-model="account" />
          </el-form-item>
          <el-form-item label="名称：">
            <el-input  v-model="name" />
          </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="questionList">搜索</el-button>
                <el-button @click="subject = '';day = '';name = '';account = ''; state = ''">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 文章列表 -->
        <el-table :data="questions" border style="width: 100%" @selection-change="handleSelectionChange">

            <el-table-column label="序号" prop="id" width="100"></el-table-column>
            <el-table-column label="账号" prop="appUserVo.account"  width="100"></el-table-column>
            <el-table-column label="名称" prop="appUserVo.name"  width="100"></el-table-column>
           <el-table-column label="时间" prop="learnDay" width="150"></el-table-column>


          <el-table-column label="类型" width="150" prop="teachingKnowledgeResp.contentValue"></el-table-column>
          <el-table-column label="阶段" width="100" prop="teachingKnowledgeResp.gradeName"></el-table-column>
          <el-table-column label="标题"  width="200px" prop="teachingKnowledgeResp.title" :show-overflow-tooltip="true"> </el-table-column>
          <el-table-column label="知识点" width="200px"  prop="teachingKnowledgeResp.content" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="学习状态" width="100px" >
            <template v-slot="scope">
              <span v-if="scope.row.learnStatus == 1">已学</span>
              <span v-else>未学</span>
            </template>
          </el-table-column>

            <el-table-column label="学习时间" width="200px" prop="updateTime"></el-table-column>



            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>


        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />


        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="questionModel" label-width="100px">
                <el-form-item label="学科类型">
                    <el-select placeholder="请选择" v-model="questionModel.subject">
                        <el-option v-for="c in subjects" :key="c.id" :label="c.subjectValue" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="阶段">
                    <el-select placeholder="请选择" v-model="questionModel.gradeType">
                        <el-option v-for="c in gradeTypes" :key="c.id" :label="c.contentValue" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="题目类型">
                    <el-select placeholder="请选择" v-model="questionModel.type"
                        :change="changeQuestionType(questionModel.type)">
                        <el-option v-for="c in questionTypes" :key="c.id" :label="c.questionValue" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="题目">
                    <el-input v-model="questionModel.content" type="textarea" style="width: 500px" />
                </el-form-item>
              <el-form-item label="正确选项" v-if="showState != 1">
                <el-select placeholder="请选择" v-model="questionModel.rightAnswer">
                  <el-option v-for="c in options" :key="c.id" :label="c.contentValue" :value="c.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="错误选项" v-if="showState != 1">
                <el-select placeholder="请选择" v-model="questionModel.wrongOption2">
                  <el-option v-for="c in options" :key="c.id" :label="c.contentValue" :value="c.id">
                  </el-option>
                </el-select>
              </el-form-item>


                <el-form-item label="正确选项" v-if="showState == 1">
                    <el-input v-model="questionModel.rightAnswer" type="text" style="width: 210px;" />
                </el-form-item>

                <el-form-item label="错误选项2"  v-if="showState == 1">
                    <el-input v-model="questionModel.wrongOption2" type="text" style="width: 210px;" />
                </el-form-item>

                <el-form-item label="错误选项3" v-if="showState == 1">
                    <el-input v-model="questionModel.wrongOption3" type="text" style="width: 210px;" />
                </el-form-item>

                <el-form-item label="错误选项4" v-if="showState == 1">
                    <el-input v-model="questionModel.wrongOption4" type="text" style="width: 210px;" />
                </el-form-item>

                <el-form-item label="配图">

                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                        action="/api/admin/upload/uploadFile" name="file" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="uploadSuccess">
                        <img v-if="questionModel.imgUrl" :src="questionModel.imgUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-icon v-if="questionModel.imgUrl" @click="delImg()">
                        <Close />
                    </el-icon>
                </el-form-item>


                <el-form-item label="音频">

                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                        action="/api/admin/upload/uploadFile" name="file" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="uploadAudioSuccess">
                        <audio v-if="questionModel.audioUrl" controls>
                            <source :src="questionModel.audioUrl">
                            <embed height="50" width="100" :src="questionModel.audioUrl">
                        </audio>
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>

                    </el-upload>
                    <el-icon v-if="questionModel.audioUrl" @click="delAudio()">
                        <Close />
                    </el-icon>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="title == '添加题目' ? addQuestion() : updateQuestion()">保存</el-button>

                </el-form-item>
            </el-form>
        </el-drawer>


    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}


/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>